package cn.lls.controller.ca;

import cn.lls.base.common.LlsEnum;
import cn.lls.base.exception.LlsException;
import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import cn.lls.base.util.MD5Util;
import cn.lls.base.util.TokenUtil;
import cn.lls.dto.CALoginDTO;
import cn.lls.req.company.CAAccountReq;
import cn.lls.service.ICompanyAccountService;
import cn.lls.service.IPermissionService;
import cn.lls.vo.common.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 单位管理员登录控制器
 *
 * @ClassName CALoginController
 * @Author 划水艺术家
 * @Date 2022/11/21 1:02
 * @Version 1.0
 **/

@RestController
@RequestMapping("/ca/login")
@Api(tags = "单位管理员-登录控制器")
@Slf4j
public class CALoginController {

    @Autowired
    private ICompanyAccountService companyAccountService;

    @Autowired
    private IPermissionService permissionService;

    @PostMapping
    @ApiOperation(value = "单位管理员登录", notes = "单位管理员登录", response = R.class, httpMethod = "POST")
    public R saLogin(@RequestBody @Validated CAAccountReq caAccountReq,
                     BindingResult bindingResult){
        CALoginDTO one = companyAccountService.caLogin(caAccountReq);
        if (one == null){
            throw new LlsException(ResultCode.ACCOUNT_NOT_EXISTS);
        }
        if (!MD5Util.MD5Encode(caAccountReq.getLoginPassword()).equals(one.getLoginPassword()))
            return R.fail(ResultCode.PWD_FALSE, "密码错误");
        LoginVO loginVO = new LoginVO();
        loginVO.setToken(TokenUtil.createToken(one.getAccountId(),
                LlsEnum.LlsIdentify.COMPANY_ADMIN));
        loginVO.setIdentify(LlsEnum.LlsIdentify.COMPANY_ADMIN);
        loginVO.setUserId(one.getAccountId());
        loginVO.setCompanyId(one.getCompanyId());
        loginVO.setMenuList(permissionService.getCompanyAdminMenu());
        loginVO.setName("管理员");
        loginVO.setOrganName(one.getOrganName());
        return R.success(loginVO);
    }

}
